/**
 * 实际使用示例：React组件中使用生成的TypeScript接口
 * 这个文件展示了如何在React组件中实际使用API
 */

import React, { useState, useEffect } from 'react';
import { client } from '../client.gen.ts';
import {
  getCourseList,
  login,
  getCurrentUser,
  getCartList,
  addToCart,
  removeFromCart,
  getUserStudyRecords
} from '../sdk.gen.ts';
import type { Course, User, CartItemDto, StudyRecordDto } from '../types.gen.ts';

// 设置基础URL
client.setConfig({
  baseUrl: 'http://localhost:8080'
});

// 设置认证token的工具函数
export const setAuthToken = (token: string | null) => {
  if (token) {
    localStorage.setItem('token', token);
    client.setConfig({
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
  } else {
    localStorage.removeItem('token');
    client.setConfig({
      headers: {}
    });
  }
};

// 获取存储的token
export const getAuthToken = () => localStorage.getItem('token');

// 初始化认证状态
export const initializeAuth = () => {
  const token = getAuthToken();
  setAuthToken(token);
};

// React Hook: 使用课程列表
export const useCourses = (page: number = 1, size: number = 10, category?: string) => {
  const [courses, setCourses] = useState<Course[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    const fetchCourses = async () => {
      setLoading(true);
      setError(null);
      
      try {
        const response = await getCourseList({
          client,
          query: { page, size }
        });
        
        if (response.data?.code === 200) {
          setCourses(response.data.data?.records || []);
          setTotal(response.data.data?.total || 0);
        } else {
          setError(response.data?.message || '获取课程失败');
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : '网络错误');
      } finally {
        setLoading(false);
      }
    };

    fetchCourses();
  }, [page, size, category]);

  return { courses, loading, error, total };
};

// React Hook: 使用用户信息
export const useCurrentUser = () => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchUser = async () => {
      setLoading(true);
      setError(null);
      
      try {
        const response = await getCurrentUser({ client });
        
        if (response.data?.code === 200) {
          setUser(response.data.data || null);
        } else {
          setError(response.data?.message || '获取用户信息失败');
        }
      } catch (err) {
        setError('网络错误，请稍后重试');
      } finally {
        setLoading(false);
      }
    };

    fetchUser();
  }, []);

  return { user, loading, error };
};

// React Hook: 使用购物车
export const useCart = () => {
  const [cartItems, setCartItems] = useState<CartItemDto[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const refreshCart = async () => {
    setLoading(true);
    setError(null);
    
    try {
      const response = await getCartList({ client });
      
      if (response.data?.code === 200) {
        setCartItems(response.data.data || []);
      } else {
        setError(response.data?.message || '获取购物车失败');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    refreshCart();
  }, []);

  const addToCartHandler = async (courseId: number, quantity: number = 1) => {
    try {
      const response = await addToCart({
        client,
        body: { courseId, quantity }
      });
      
      if (response.data?.code === 200) {
        await refreshCart();
        return { success: true, message: '添加成功' };
      } else {
        return { success: false, message: response.data?.message || '添加失败' };
      }
    } catch (err) {
      return { success: false, message: '网络错误，请稍后重试' };
    }
  };

  const removeFromCartHandler = async (cartItemId: number) => {
    try {
      const response = await removeFromCart({
        client,
        path: { courseId: cartItemId }
      });
      
      if (response.data?.code === 200) {
        await refreshCart();
        return { success: true, message: '移除成功' };
      } else {
        return { success: false, message: response.data?.message || '移除失败' };
      }
    } catch (err) {
      return { success: false, message: '网络错误，请稍后重试' };
    }
  };

  return {
    cartItems,
    loading,
    error,
    refreshCart,
    addToCart: addToCartHandler,
    removeFromCart: removeFromCartHandler
  };
};

// 自定义Hook：获取学习记录
export function useStudyRecords() {
  const [records, setRecords] = useState<StudyRecordDto[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchRecords() {
      setLoading(true);
      setError(null);
      
      try {
        const response = await getUserStudyRecords({ 
          client,
          query: { userId: 1 } // 这里应该使用实际的用户ID
        });
        
        if (response.data?.code === 200) {
          setRecords(response.data.data?.records || []);
        } else {
          setError(response.data?.message || '获取学习记录失败');
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : '网络错误');
      } finally {
        setLoading(false);
      }
    }

    fetchRecords();
  }, []);

  return { records, loading, error };
}

// 示例组件：课程列表
export const CourseList: React.FC = () => {
  const { courses, loading, error } = useCourses();

  if (loading) return <div>加载中...</div>;
  if (error) return <div>错误: {error}</div>;

  return (
    <div>
      <h2>课程列表</h2>
      {courses.map(course => (
        <div key={course.id}>
          <h3>{course.title}</h3>
          <p>{course.description}</p>
          <p>价格: ¥{course.price}</p>
        </div>
      ))}
    </div>
  );
};

// 示例组件：用户登录表单
export const LoginForm: React.FC = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    
    try {
      const response = await login({
        client,
        body: { usernameOrEmail: username, password }
      });
      
      if (response.data?.code === 200) {
        // 登录成功，cookie已自动设置
        window.location.reload();
      } else {
        setError(response.data?.message || '登录失败');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleLogin}>
      <div>
        <label>用户名/邮箱:</label>
        <input
          type="text"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          required
        />
      </div>
      <div>
        <label>密码:</label>
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          required
        />
      </div>
      {error && <div style={{ color: 'red' }}>{error}</div>}
      <button type="submit" disabled={loading}>
        {loading ? '登录中...' : '登录'}
      </button>
    </form>
  );
};

// 初始化认证
initializeAuth();